/**
 * 支付相关服务
 */

const util = require('../utils/util.js');
const api = require('../config/api.js');

/**
 * 判断用户是否登录
 */
function payOrder(trade_sn) {
  return new Promise(function(resolve, reject) {
    util.request(api.WXPayPrepayId, {
      openid: app.globalData.token,
      trade_sn: trade_sn
    }).then((res) => {
      console.log(res)
      if (res.errno === 0) {
        wx.requestPayment({
          'timeStamp': res.timeStamp,
          'nonceStr': res.nonceStr,
          'package': res.package,
          'signType': res.signType,
          'paySign': res.paySign,
          'success': function(res) {
            wx.setStorageSync('trade_sn', trade_sn);
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=true',
            })
          },
          'fail': function(res) {
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=false',
            })
          },
          'complete': function(res) {
            reject(res);
          }
        })
      } else {
        reject(res);
      }
    });
  });
}


module.exports = {
  payOrder,
};